/**
 * Copyright (C) 2014
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package psn.shan.xml.enhancedvalidator.rules;

import java.util.List;
import java.util.Vector;

import javax.inject.Named;

import lombok.extern.slf4j.Slf4j;

import org.jdom2.Document;
import org.jdom2.Element;
import org.springframework.context.annotation.Scope;

/**
 * DynamicSourceRule
 * Rule implementing validation against a dynamic source.
 * 
 * @author Shan
 * 
 */
@Named("StaticComparisonRule")
@Scope("prototype")
@Slf4j
public class StaticComparisonRule extends AbstractLinkedRule {
	static {
		mRuleType = RuleType.STATIC_COMPARISON;		
	}

	/* (non-Javadoc)
	 * @see psn.shan.xml.declarativevalidator.rules.AbstractBaseRule#applyRule()
	 */
	@Override
	public List<String> applyRule(Document aInput) {
		List<Element> lElements = getRuledSubjects(aInput);

		List<String> lMessages = new Vector<String>(); 

		for (Element lMatch : lElements) {
			String lMatchedValue = lMatch.getValue();
			log.debug("Matched element is " + lMatch.getName() + " with value " + lMatchedValue);

			List<List<Element>> lReferences = getReferredElements(lMatch); 
			String lReferredValue = lReferences.get(0).get(0).getValue();
			log.debug("Referred element is " + lReferredValue);
			
			try {
				getComparator().setOperandOne(lMatchedValue);
				getComparator().setOperandTwo(lReferredValue);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if (getComparator().evaluate()) {
				setException(getException().replace(VALUE_VARIABLE, lMatchedValue));
				setException(getException().replace(REFERENCE_VARIABLE, lReferredValue));
				lMessages.add(getException());
			}
		}

		return lMessages;
	}

}
